package com.franklin.icharm;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import com.franklin.icharm.service.MainService;
//import com.nichtemna.takeandsavephoto.PhotoActivity;

import android.os.Bundle;
import android.accounts.Account;
/*import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;*/
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

	public static boolean forStandaloneDebug = false;

	private static final int REQ_BT_ENABLE = 1;
	private static final int PAIRING_REQUEST = 2;
	private static final int MAIN_MENU_REQUEST = 3;

	private static final String TAG = "MainActivity";
	private boolean deviceConnected = false;
//	public static HashMap<String, Double> map;
	private UserConfig mUserConfig ;
	private ComponentName mServiceName = null;
	private BroadcastReceiver mBcRec = null;
	private boolean isLostLink = false;

	Timer timer = new Timer();
	private BluetoothAdapter myBTadapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mUserConfig = new UserConfig(this);
	//	dummyConfig();
       	String email = mUserConfig.getConfString(UserConfig.KV_USER_EMAIL, null );
       	if (email == null)
       		startAccountList();
       	else
       		startup();

       	mBcRec = new BroadcastReceiver()
       	{
    		@Override
    		public void onReceive(Context context, Intent intent)
    		{
    			String action = intent.getAction();
    			if (MainService.ACTION_DISCONNECTED_DEVICE.equals(action))
    			{
    				Log.i(TAG, "ACTION_DISCONNECTED_DEVICE");
    				isLostLink = true;
    				stopMainService();
    				Timer t1 = new Timer();
    				t1.schedule(new TimerTask()
    				{
    					@Override
    					public void run()
    					{
    						startMainService();
    					} // run
    				}, 1000);
    			}
    			else
    			{
    				if (isLostLink)
    				{
    					if (MainService.ACTION_SERVICE_STARTED.equals(action))
    					{
    						Intent startScan = new Intent();
    						startScan.setAction(MainService.ACTION_APP_BLE_SCANNING);
    						startScan.putExtra(MainService.EXTRA_ENABLE, true);
    						sendBroadcast(startScan);
    						Log.i(TAG, "ACTION_SERVICE_STARTED");
    						Timer t2 = new Timer();
    						t2.schedule(new TimerTask()
    						{	// Stop scanning if device not found in 30 seconds.
    							@Override
    							public void run()
    							{
    								isLostLink = false;
        							Intent reconnect = new Intent();
        							reconnect.setAction(MainService.ACTION_APP_BLE_SCANNING);
        							reconnect.putExtra(MainService.EXTRA_ENABLE, false);
        							sendBroadcast(reconnect);
    							} // run
    						}, 30000);
    					}
    					else if (MainService.ACTION_SCANNED_DEVICE.equals(action))
    					{
    						String daddress = intent.getExtras().getString(MainService.EXTRA_DEVICE_ADDRESS);
    						if (PairingActivity.mDeviceAddr.equals(daddress))
    						{
    							Intent reconnect = new Intent();
    							reconnect.setAction(MainService.ACTION_APP_BLE_SCANNING);
    							reconnect.putExtra(MainService.EXTRA_ENABLE, false);
    							sendBroadcast(reconnect);
    							reconnect = new Intent();
    							reconnect.setAction(MainService.ACTION_APP_GO_CONNECTION);
   								reconnect.putExtra(MainService.EXTRA_DEVICE_ADDRESS, daddress);
    							sendBroadcast(reconnect);
    							Log.i(TAG, "ACTION_APP_GO_CONNECTION -> addr = " + daddress);
    							isLostLink = false;
    						} // if
    					} // if-else-if
    				} // if
    			} // if-else
    		} // onReceive
       	};
       	IntentFilter iFilter = new IntentFilter(MainService.ACTION_DISCONNECTED_DEVICE);
       	iFilter.addAction(MainService.ACTION_SERVICE_STARTED);
       	iFilter.addAction(MainService.ACTION_SCANNED_DEVICE);
       	registerReceiver(mBcRec, iFilter);
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		Log.i(TAG, "MainActivity destroyed");
		unregisterReceiver(mBcRec);
		stopMainService();
	} // onDestroy

	private void startMainService()
	{
		if (!isMyServiceRunning(this))
		{
			Log.d(TAG, "@_@ Starting service");
			Intent pushIntent = new Intent(this, MainService.class);
			mServiceName = startService(pushIntent);
			Log.i(TAG, "Service name = " + mServiceName.getClassName());
		}
		else
			Log.d(TAG, "@_@ already run service");
	} // startMainService

	private void stopMainService()
	{
		if (mServiceName != null)
		{
			Intent intent = new Intent();
			intent.setComponent(mServiceName);
			stopService(intent);
		} // if
	} // stopMainService

	private void startup()
	{
		if (forStandaloneDebug)
		{
			launchSettingActivity();
			return;
		}

//		timer.schedule(task, 1000); // timeTask
		myBTadapter=BluetoothAdapter.getDefaultAdapter();

		ImageView iv=(ImageView)findViewById(R.id.iv);
		iv.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				timer.cancel();
				if (deviceConnected){
					launchSettingActivity();
				}
				else{
					launchPairingActivity();
				}
			}
		});

		startMainService();

		if (CheckBlueTooth())
		{
			deviceConnected = CheckConnectedDevice();
			if (deviceConnected)
				launchSettingActivity();
			else
				launchPairingActivity();
		}
		Log.d(TAG, "deviceConnected = " + deviceConnected);
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (requestCode)
		{
			case PAIRING_REQUEST:
				if (resultCode == RESULT_OK)
					launchSettingActivity();
				else
					finish();
				break;
			case REQ_BT_ENABLE:
				if (resultCode == RESULT_OK)
					launchPairingActivity();
				else
					finish();
				break;
			case MAIN_MENU_REQUEST:
				finish();
		} // switch
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void launchSettingActivity()
	{
		Intent intent=new Intent();
		intent.setClass(MainActivity.this, MainMenuActivity.class);
		startActivityForResult(intent, MAIN_MENU_REQUEST);
	}

	private void launchPairingActivity()
	{
		Intent intent=new Intent();

		intent.setClass(MainActivity.this, PairingActivity.class);
		startActivityForResult(intent, PAIRING_REQUEST);
	}

	private boolean isMyServiceRunning(Context context) {
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			if (MainService.class.getName().equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}


	private boolean CheckBlueTooth()
	{

		// Initializes a Bluetooth deviceListAdapter. For API level 18 and above, get a
		// reference to BluetoothAdapter through BluetoothManager.
		if(myBTadapter==null)
		{
			Toast.makeText(getApplicationContext(), R.string.bt_not_supported, Toast.LENGTH_LONG).show();
			return false;
		}
		if(!myBTadapter.isEnabled())
		{
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
			startActivityForResult(enableBtIntent, REQ_BT_ENABLE);
			Log.i(TAG, getString(R.string.bt_enabling));
//			Toast.makeText(getApplicationContext(), R.string.bt_enabling, Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}

	private boolean CheckConnectedDevice()
	{
/*		UserConfig uc = new UserConfig(this);
		return uc.getConfBoolean(UserConfig.KV_DEVICE_CONNECTED , false);*/
		return MainService.isConnected();
	}

/*	private final TimerTask task = new TimerTask() {
		@Override
		public void run() {

			runOnUiThread(new Runnable() { // UI thread
				@Override
				public void run() {
					{
						timer.cancel();
						if (deviceConnected){
							launchSettingActivity();

						}
						else{
							launchPairingActivity();
						}

					}
				}
			});
		}
	};*/

	public void dummyConfig()
	{

		UserConfig uc = new UserConfig(this);
		uc.setConf(UserConfig.KV_VIP_NOTIFY, true);
		uc.setConf(UserConfig.KV_VIP_NAME, "Paul");

		uc.setConf(UserConfig.KV_CALL0_NOTIFY.replace("{0}", "1"), true);
		uc.setConf(UserConfig.KV_CALL0_NAMES1.replace("{0}", "1").replace("{1}", "0"), "Paul");
		uc.setConf(UserConfig.KV_CALL0_NOTIFY.replace("{0}", "2"), true);
		uc.setConf(UserConfig.KV_CALL0_NAMES1.replace("{0}", "2").replace("{1}", "0"), "Paul");
		uc.setConf(UserConfig.KV_CALL0_NOTIFY.replace("{0}", "3"), true);
		uc.setConf(UserConfig.KV_CALL0_NAMES1.replace("{0}", "3").replace("{1}", "0"), "Paul");
		uc.setConf(UserConfig.KV_CALL0_NOTIFY.replace("{0}", "4"), true);
		uc.setConf(UserConfig.KV_CALL0_NAMES1.replace("{0}", "4").replace("{1}", "0"), "Paul");
		uc.setConf(UserConfig.KV_CALL0_TOTAL_NAME.replace("{0}", "1"), 1);
		uc.setConf(UserConfig.KV_CALL0_TOTAL_NAME.replace("{0}", "2"), 1);
		uc.setConf(UserConfig.KV_CALL0_TOTAL_NAME.replace("{0}", "3"), 1);
		uc.setConf(UserConfig.KV_CALL0_TOTAL_NAME.replace("{0}", "4"), 1);
		
		uc.setConf(UserConfig.KV_APP0_NOTIFY.replace("{0}", "1"), true);
		uc.setConf(UserConfig.KV_APP0_NAME.replace("{0}", "1"), "SMS");

		uc.setConf(UserConfig.KV_APP0_NOTIFY.replace("{0}", "4"), true);
		uc.setConf(UserConfig.KV_APP0_NAME.replace("{0}", "4"), "Mail");	
		uc.setConf(UserConfig.KV_SETTING_OUTOFRANGE, true);
		uc.setConf(UserConfig.KV_APP0_NOTIFY.replace("{0}", "3"), true);
		uc.setConf(UserConfig.KV_APP0_NAME.replace("{0}", "3"), "Calendar");	
		uc.setConf(UserConfig.KV_SETTING_OUTOFRANGE, true);
		
	}
	
	public void selectEmail(Account[] accounts)
	{
		AlertDialog.Builder builderSingle = new AlertDialog.Builder(
				MainActivity.this);
        builderSingle.setIcon(R.drawable.ic_launcher);
        builderSingle.setTitle("Select One Name:-");
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
        		MainActivity.this,
                android.R.layout.select_dialog_singlechoice);
		for (int i = 0; i< accounts.length ; i++)
			 arrayAdapter.add(accounts[i].name);

        builderSingle.setNegativeButton("cancel",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });

        builderSingle.setAdapter(arrayAdapter,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final String strName = arrayAdapter.getItem(which);
                       	mUserConfig.setConf(UserConfig.KV_USER_EMAIL,strName );
                        dialog.dismiss();
                        startup();
                   
                    }
                });
        builderSingle.show();
	}

//	private static final String ACCOUNT_TYPE_GOOGLE = "com.google";
//	private static final String[] FEATURES_MAIL = {"service_mail"};

	
	public void startAccountList()
	{
		SelectEmailDialog.Callback callback = new SelectEmailDialog.Callback()
		{
			Account[] emailAddresses = null;

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				switch (which)
				{
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						finish();
						break;
					default:
						if (which >= 0)
						{
							String strName = emailAddresses[which].name;
							Log.i(TAG, strName);
							mUserConfig.setConf(UserConfig.KV_USER_EMAIL,strName );
							dialog.dismiss();
							startup();
						} // if
				} // switch
			} // onClick

			@Override
			public void onShow(Account[] accounts)
			{
				emailAddresses = accounts;
			} // onShow
		};
		new SelectEmailDialog(this, callback);
		// Get the account list, and pick the first one
/*		AccountManager.get(this).getAccountsByTypeAndFeatures(ACCOUNT_TYPE_GOOGLE, FEATURES_MAIL,
				new AccountManagerCallback<Account[]>() {
					@Override
					public void run(AccountManagerFuture<Account[]> future) {
						Account[] accounts = null;
						try {
							accounts = future.getResult();
						} catch (OperationCanceledException oce) {
							Log.e(TAG, "Got OperationCanceledException", oce);
						} catch (IOException ioe) {
							Log.e(TAG, "Got OperationCanceledException", ioe);
						} catch (AuthenticatorException ae) {
							Log.e(TAG, "Got OperationCanceledException", ae);
						}
						onAccountResults(accounts);
					}*/
//				}, null /* handler */);
	}

/*	private void onAccountResults(Account[] accounts) {
		Log.i(TAG, "received accounts: " + Arrays.toString(accounts));
		 selectEmail(accounts);
	}*/

}
